package vn.axonactive.devday.jsf.session4;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.push.PushContext;
import org.primefaces.push.PushContextFactory;

import vn.axonactive.devday.jsf.model.StockQuote;
import vn.axonactive.devday.jsf.model.stockfeed.StockQuoteFactory;

/**
 * An extension of {@link StockBoardBean} which is used to demonstrate PrimeFaces Push function. Automatically it simulates the fluctuation of {@link StockQuote}, open channel and
 * push changing data to the client. 
 *
 */
@ManagedBean
@SessionScoped
public class StockBoardPushBean extends StockBoardBean implements Runnable {
	
	private static final long serialVersionUID = 3177639667194690243L;
	
	private transient Thread thread;
	
	public StockBoardPushBean() {
		super();
		
		thread = new Thread(this);
		thread.setDaemon(true);
        thread.start();
	}
	
	@Override
	public void run() {
		while(true)
		{
			//update the list
			StockQuoteFactory.getInstance().simulateFluctuation(getStockQuoteList());
			
			//push data to server
			PushContext pushContext = PushContextFactory.getDefault().getPushContext();
	        pushContext.push("/stockQuotes", String.valueOf(getStockQuoteList()));
	        
			
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO add log
				throw new IllegalStateException(e);
			}
		}
		
	}
}
